//
//  tb2ViewController.m
//  Lesson
//
//  Created by centling on 15/4/15.
//  Copyright (c) 2015年 Seas.CHENG. All rights reserved.
//

#import "tb2ViewController.h"
#import "tbCellTableViewCell.h"
#import "User.h"
#import "WeatherTableViewCell.h"
#import "IndexTableViewCell.h"
#import "UIImageView+WebCache.h"
//#import "AFNetworking.h"
//#import "global.h"

#import "NetClient.h"

@interface tb2ViewController ()

@end

@implementation tb2ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableview.delegate=self;
    self.tableview.dataSource=self;
    self.city=@"北京";
    
    //设定搜索栏ScopeBar隐藏
    [self.searchBar setShowsScopeBar:NO];
    [self.searchBar sizeToFit];
    
    [self loadWeather];
    
    
//    //注意：最后使用的url是baseURL+"/"+url, 所以要注意分割出baseURL
//    static NSString *const baseURLstr=@"http://api.map.baidu.com/telematics/v3";
//    NSURL *baseURL=[NSURL URLWithString:baseURLstr];
//    
//    
//    //从plist文件中读取BundleIdentifier
//    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Info"
//                                                          ofType:@"plist"];
//    NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
//    NSString *bundleIdentifier=[dictionary objectForKey:@"CFBundleIdentifier"];
//
//    
//    //url的UTF8编码
//    NSString *url=[NSString stringWithFormat:@"weather?location=%@&output=json&ak=%@&mcode=%@",@"青岛",baiduAK,bundleIdentifier];
//    NSString *encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//
//    //发起网络请求
//    AFHTTPSessionManager *manager=[[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
//    [manager GET:encodedUrl parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
//        NSLog(@"返回成功：%@",responseObject);
//    } failure:^(NSURLSessionDataTask *task, NSError *error) {
//        NSLog(@"返回错误：%@",error);
//    }];
    
    // Do any additional setup after loading the view.
}


-(void)loadWeather{
    NSLog(@"%@",self.city);
    
    id block = ^(Weather *weather, NSError *error){
        if (error==nil) {
            NSLog(@"返回成功:%@",weather);
            NSArray *tmpArray=weather.results;
            Result *result=[tmpArray objectAtIndex:0];
            self.weatherArray=[[NSArray alloc] initWithArray:result.weather_data];
            self.indexArray=[[NSArray alloc] initWithArray:result.index];
            [self.tableview reloadData];
        }else{
            NSLog(@"返回失败:%@",error);
        }
    };
    
    [[NetClient instance] getWeather:self.city completionBlock:block];
//    -(void)getWeather:(NSString *)city completionBlock:(void(^)(Weather *weather, NSError *error))block{

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark TableView


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==0) {
        UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 50)];
        view.backgroundColor=[UIColor lightGrayColor];
        self.cityLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 50)];
        self.cityLabel.textAlignment=UITextAlignmentCenter;
        self.cityLabel.text=self.city;
        [view addSubview:self.cityLabel];
        return view;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return 50;
            break;
        default:
            break;
    }
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
            return 110;
            break;
        case 1:
            return 135;
            break;
        default:
            break;
    }
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 2;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return [self.weatherArray count];
            break;
        case 1:
            return [self.indexArray count];
            break;
            
        default:
            break;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.section) {
        case 0:{
            static NSString *cellStr=@"weatherCell";
            WeatherTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellStr];
            if (cell==nil) {
                cell=[[WeatherTableViewCell alloc] init];
            }
            
            Data *data=(Data *)[self.weatherArray objectAtIndex:indexPath.row];
            cell.date.text=data.date;
            cell.weather.text=data.weather;
            cell.wind.text=data.wind;
            cell.temperature.text=data.temperature;
            [cell.dayPictureUrl sd_setImageWithURL:[NSURL URLWithString:data.dayPictureUrl]];
            [cell.nightPictureUrl sd_setImageWithURL:[NSURL URLWithString:data.nightPictureUrl]];
            
            return cell;
            break;
        }
           
        case 1:{
            static NSString *cellStr=@"indexCell";
            IndexTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellStr];
            if (cell==nil) {
                cell=[[IndexTableViewCell alloc] init];
            }
            
            Index *index=(Index *)[self.indexArray objectAtIndex:indexPath.row];
            cell.title.text=index.title;
            cell.zs.text=index.zs;
            cell.tipt.text=index.tipt;
            cell.des.text=index.des;
            return cell;
            break;
        }
        default:
            break;
    }
    
    return nil;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"点击了：%ld",(long)indexPath.row);
}


- (IBAction)backButtonClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark Locaiton

-(void)viewWillAppear:(BOOL)animated{
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager=[[CLLocationManager alloc] init];
        self.locationManager.delegate=self;
    }else{
        //提示用户无法开启定位功能
    }
}

- (IBAction)getLocation:(id)sender{
    [self.locationManager startUpdatingLocation];
}


-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *currentLocation=[locations lastObject];
    CLLocationCoordinate2D coor=currentLocation.coordinate;
    
    CLLocation *location=[[CLLocation alloc] initWithLatitude:coor.latitude longitude:coor.longitude];
    //创建位置
    CLGeocoder *revGeo=[[CLGeocoder alloc] init];
    
    //反向地理位置编码：
    [revGeo reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (!error &&[placemarks count]>0) {
            NSDictionary *dic=[[placemarks objectAtIndex:0] addressDictionary];
            NSLog(@"%@",dic);
            self.city=[dic objectForKey:@"City"];
            [self loadWeather];
        }
    }];
    
    [self.locationManager stopUpdatingLocation];
    
}


@end
